<template>
  <view class="container">
    <!-- 头部标题 -->
    <view class="helbet">您的反馈内容:</view>
    <!-- 表单容器 -->
    <view class="form-container">
      <!-- 问题描述输入框 -->
      <view class="form-item" style="height: 600rpx;">
       <textarea 
          class="textarea" 
          placeholder="有什么需要反馈，留下信息，我们会尽快帮您解决！请你详细描述，200字以内。" 
          v-model="feedback.content"
          maxlength="500"
          auto-height
        ></textarea>
        <view class="word-count">{{ feedback.content.length }}/500</view>
        <!-- 错误提示 -->
        <view class="error-message" v-if="errors.content">{{ errors.content }}</view>
      </view>

      <!-- 上传图片区域 -->
      <view class="form-item" style="background-color: #F8F8F8;">
        <view class="label">上传图片</view>
        <view class="upload-container">
          <!-- 已上传图片预览 -->
          <view class="preview-images">
            <view 
              class="image-item" 
              v-for="(image, index) in feedback.images" 
              :key="index"
              @click="previewImage(index)"
            >
              <image :src="image" mode="aspectFill"></image>
              <view class="delete-btn" @click="removeImage(index)">
                <image src="/static/de.png" mode="widthFix"></image>
              </view>
            </view>
          </view>
          
          <!-- 上传按钮 -->
          <view class="upload-btn" @click="chooseImage" v-if="feedback.images.length < 5">
            <image src="/static/my/xj.png" mode="widthFix"></image>
            <view class="upload-text">点击上传</view>
          </view>
          
          <!-- 上传进度条 -->
          <view class="upload-progress" v-if="uploading">
            <view class="progress-bar">
              <view class="progress-inner" :style="{ width: uploadProgress + '%' }"></view>
            </view>
            <view class="progress-text">{{ uploadProgress }}%</view>
          </view>
        </view>
        <!-- 错误提示 -->
        <view class="error-message" v-if="errors.images">{{ errors.images }}</view>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitFeedback">
      提交反馈
    </view>
  </view>
</template>

<script>
import  { FeedBack } from '@/core/api/index.js'
import { mapState } from 'vuex';
export default {
  data() {
    return {
      feedback: {
        content: '',  // 反馈内容
        images: []    // 上传的图片路径
      },
      errors: {
        content: '',  // 内容错误信息
        images: ''    // 图片错误信息
      },
      uploading: false,        // 上传中状态
      uploadProgress: 0,       // 上传进度
      uploadQueue: 0,          // 上传队列长度
      uploadedCount: 0,        // 已上传数量
      isLoading: false         // 加载状态
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  methods: {
    // 选择并上传图片
    chooseImage() {
      if (this.isLoading) return;
      
      uni.chooseImage({
        count: 5 - this.feedback.images.length, // 最多选择剩余可上传数量
        sizeType: ['compressed'], 
        sourceType: ['album', 'camera'], 
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          if (tempFilePaths.length === 0) return;
          
          this.isLoading = true;
          this.uploading = true;
          this.uploadQueue = tempFilePaths.length;
          this.uploadedCount = 0;
          this.uploadProgress = 0;
          
          // 多张图片上传
          tempFilePaths.forEach((filePath, index) => {
            this.uploadImage(filePath);
          });
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 上传单张图片
    uploadImage(filePath) {
      uni.uploadFile({
        url: 'https://shequ.shihongkeji.cn' + '/webapi/file/upload',
        filePath: filePath,
        name: "file",
        header: {
          'token': uni.getStorageSync('token')
        },
        success: (uploadFileRes) => {
          try {
            const uplodata = JSON.parse(uploadFileRes.data);
            if (uplodata.code == '00000') {
              this.feedback.images.push('https:' + uplodata.result.filePath);
            } else {
              uni.showToast({
                title: '图片上传失败',
                icon: 'none'
              });
            }
          } catch (e) {
            console.error('解析上传结果失败:', e);
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
          }
        },
        fail: (uploadFileErr) => {
          console.error('上传失败:', uploadFileErr);
          uni.showToast({
            title: '图片上传失败',
            icon: 'none'
          });
        },
        complete: () => {
          // 更新上传进度
          this.uploadedCount++;
          this.updateProgress();
          
          // 所有图片上传完成
          if (this.uploadedCount === this.uploadQueue) {
            setTimeout(() => {
              this.isLoading = false;
              this.uploading = false;
              uni.showToast({
                title: `成功上传${this.uploadQueue}张图片`,
                icon: 'success'
              });
            }, 300);
          }
        }
      });
    },
    
    // 更新上传进度
    updateProgress() {
      this.uploadProgress = Math.floor((this.uploadedCount / this.uploadQueue) * 100);
    },
    
    // 查看图片
    previewImage(index) {
      uni.previewImage({
        current: this.feedback.images[index],
        urls: this.feedback.images
      });
    },
    
    // 删除图片
    removeImage(index) {
      this.feedback.images.splice(index, 1);
    },
    
    // 表单验证
    validateForm() {
      let isValid = true;
      this.errors = { content: '', images: '' };
      
      if (!this.feedback.content.trim()) {
        this.errors.content = '请填写问题描述';
        isValid = false;
      } else if (this.feedback.content.length < 10) {
        this.errors.content = '问题描述至少需要10个字符';
        isValid = false;
      }
      
      if (this.feedback.images.length === 0) {
        this.errors.images = '请上传至少一张图片';
        isValid = false;
      }
      
      return isValid;
    },
    
    // 提交反馈
    async submitFeedback() {
      if (!this.validateForm()) return;
      uni.showLoading({ title: '提交中...', mask: true });
	  let prmes = {
		  content:this.feedback.content,
		  images:this.feedback.images,
		  merchantId:this.userInfo.shopId,
		  merchantName:this.userInfo.shopName
	  }
	  const data = await FeedBack(prmes)
	  if(data.code != '00000') return
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '提交成功，感谢您的反馈！',
          icon: 'success',
          duration: 2000
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      }, 100);
    }
  }
}
</script>

<style lang="scss">
.container {
  height: 100vh;
  padding: 0 30rpx;
}

.helbet {
  font-size: 32rpx;
  color: #333;
  margin: 34rpx 0;
}

.form-container {
  margin-top: 20rpx;
  padding: 20rpx -30rpx 0;
  
  .form-item {
    padding: 30rpx;
    background-color: #fff;
    border-radius: 10rpx;
    
    .label {
      font-size: 32rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .textarea {
      width: 100%;
      font-size: 28rpx;
      color: #929292;
      height: 96% !important;
      line-height: 40rpx;
    }
    
    .word-count {
      text-align: right;
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
    }
    
    .upload-container {
      display: flex;
      flex-wrap: wrap;
      
      .preview-images {
        display: flex;
        flex-wrap: wrap;
        margin-right: -20rpx;
      }
      
      .image-item {
        position: relative;
        width: 160rpx;
        height: 160rpx;
        margin-right: 30rpx;
        margin-bottom: 20rpx;
        border-radius: 12rpx;
        
        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .delete-btn {
          position: absolute;
          top: -12rpx;
          right: -12rpx;
          width: 36rpx;
          height: 36rpx;
          background-color: rgba(0,0,0,0.6);
          color: #fff;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24rpx;
        }
      }
      
      .upload-btn {
        width: 160rpx;
        height: 160rpx;
        border-radius: 12rpx;
        display: flex;
        background-color: #fff;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #000;
        
        image {
          width: 40rpx;
          margin-bottom: 20rpx;
        }
        
        .upload-text {
          font-size: 24rpx;
        }
      }
      
      // 新增：上传进度条样式
      .upload-progress {
        width: 100%;
        margin-top: 20rpx;
        
        .progress-bar {
          width: 100%;
          height: 8rpx;
          background-color: #E5E5E5;
          border-radius: 4rpx;
          overflow: hidden;
          
          .progress-inner {
            height: 100%;
            background-color: #F26B2E;
            border-radius: 4rpx;
            transition: width 0.2s;
          }
        }
        
        .progress-text {
          font-size: 24rpx;
          color: #999;
          text-align: center;
          margin-top: 10rpx;
        }
      }
    }
    
    .error-message {
      color: #ff3b30;
      font-size: 24rpx;
      margin-top: 10rpx;
    }
  }
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  background: var(--Color, #F26B2E);
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin: 60rpx 0;
}
</style>